<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      append-to-body
      clas="t-dialog"
      :title="$t('form.configParams.configTemplateVariables')"
    >
      <div class="desc-text">
        {{ $t("form.configParams.selectFormFieldComponents") }}

        <el-link
          href="/msg/template"
          type="primary"
          :underline="false"
          target="_blank"
        >
          {{ $t("form.configParams.configureMessageTemplate") }}
        </el-link>
      </div>
      <div class="content-wrap">
        <div class="left-wrap">
          <el-form
            v-if="!loading"
            class="mt10"
            label-position="top"
          >
            <div v-if="dynamicFields.length == 0">
              <el-empty :description="$t('form.configParams.templateNotConfigured')" />
            </div>

            <el-form-item
              v-for="field in dynamicFields"
              :key="field"
            >
              <template #label>
                {{ $t("form.configParams.templateVariables") }}
                <el-tag type="info">
                  {{ field }}
                </el-tag>
                {{ $t("form.configParams.formComponents") }}
                <el-select
                  class="select-width"
                  size="default"
                  v-model="templateParamMapping[field]"
                >
                  <el-option
                    v-for="item in fields"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-form-item>
          </el-form>
        </div>
        <div class="right-wrap">
          <div
            class="template-content"
            v-html="formatTemplateContent"
          ></div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            size="default"
            @click="dialogVisible = false"
          >
            {{ $t("formI18n.all.cancel") }}
          </el-button>
          <el-button
            size="default"
            type="primary"
            @click="handleSubmit"
          >
            {{ $t("formI18n.all.confirm") }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ConfigParams">
import { PropType, defineProps, reactive, ref, onMounted, computed } from "vue";
import { MsgTemplate } from "@/api/system/msgtemplate";
import { FieldItem } from "@/api/project/form";

const props = defineProps({
  templateList: {
    type: Array as PropType<MsgTemplate[]>,
    default: () => []
  },
  selectTemplateId: {
    type: Number,
    default: 0
  },
  // 表单字段列表
  fields: {
    type: Array as PropType<FieldItem[]>,
    default: () => []
  }
});

const templateParamMapping = reactive<{ [key: string]: any }>({});
const dialogVisible = ref(false);
const dynamicFields = ref<string[]>([]);
const loading = ref(true);
const templateContent = ref("");

const show = (params: any) => {
  dialogVisible.value = true;
  loading.value = true;
  const item = props.templateList.find(item => item.id === props.selectTemplateId);
  if (item) {
    dynamicFields.value = [];
    const regex = /\${([^}]+)}/g;
    const matches = item.templateContent.matchAll(regex);
    for (const match of matches) {
      const extractedString = match[1];
      dynamicFields.value.push(extractedString);
    }
  }
  let initVal = params || {};
  dynamicFields.value.forEach(field => {
    templateParamMapping[field] = initVal[field];
  });
  templateContent.value = item?.templateContent || "";
  loading.value = false;
};

const formatTemplateContent = computed(() => {
  let formatContent = templateContent.value;
  Object.keys(templateParamMapping).forEach((key: string) => {
    if (templateParamMapping[key]) {
      const item = props.fields.find(item => item.value === templateParamMapping[key]);
      formatContent = formatContent.replace("${" + key + "}", item?.label || "");
    }
  });
  return formatContent;
});

defineExpose({
  show
});

const emit = defineEmits(["submit"]);

const handleSubmit = () => {
  dialogVisible.value = false;
  emit("submit", templateParamMapping);
};

onMounted(() => {});
</script>
<style lang="scss" scoped>
.content-wrap {
  display: flex;
}
.left-wrap {
  width: 50%;
}
.right-wrap {
  width: 50%;
  margin-top: 20px;
  background: #f5f7fa;
  border-radius: 10px;
}
.template-content {
  padding: 20px;
}
.select-width {
  width: 40% !important;
}
</style>
